import os
from django.http import JsonResponse
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from PIL import Image
from io import BytesIO
from fitz import Document as PDFDocument
from django.http import HttpResponse
from docx import Document
from jinja2 import Environment, FileSystemLoader


def image_to_pdf(request, image_path):
    try:
        # 打开图片
        img = Image.open(image_path)
        img_byte_arr = BytesIO()
        img.save(img_byte_arr, format='PNG')
        img_byte_arr = img_byte_arr.getvalue()

        # 创建PDF画布
        p = canvas.Canvas("output.pdf", pagesize=letter)
        # 将图片添加到PDF
        p.drawImage(img_byte_arr, 0, 0, width=img.width, height=img.height)
        # 保存PDF
        p.save()

        # 返回PDF文件路径
        return JsonResponse({'message': 'Single image to PDF conversion successful.', 'pdf_path': 'output.pdf'},
                            status=200)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=400)


def images_to_pdf(request, image_paths):
    try:
        # 创建PDF画布
        p = canvas.Canvas("output.pdf", pagesize=letter)

        for image_path in image_paths:
            img = Image.open(image_path)
            # 确保图片宽度小于高度
            if img.width >= img.height:
                img = img.transpose(Image.ROTATE_90)
            img_byte_arr = BytesIO()
            img.save(img_byte_arr, format='PNG')
            img_byte_arr = img_byte_arr.getvalue()
            # 将图片添加到PDF
            p.drawImage(img_byte_arr, 0, 0, width=img.width, height=img.height)

        # 保存PDF
        p.save()

        # 返回PDF文件路径
        return JsonResponse({'message': 'Images to PDF conversion successful.', 'pdf_path': 'output.pdf'}, status=200)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=400)


def compress_pdf(request, pdf_path, output_path):
    try:
        # 使用PyMuPDF压缩PDF
        doc = PDFDocument(pdf_path)
        doc.save(output_path, garbage=4, deflate=True, clean=True)
        doc.close()

        return JsonResponse({'message': 'PDF compression successful.', 'compressed_pdf_path': output_path}, status=200)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=400)


def generate_word_document(request):
    # 加载模板
    file_loader = FileSystemLoader('path_to_templates')  # 模板文件存放的路径
    env = Environment(loader=file_loader)
    template = env.get_template('template.docx')  # 模板文件名

    # 从数据库或表单获取变量
    # 假设使用Django的表单或模型来获取数据
    # variables = MyModel.objects.values('name', 'other_field')  # 示例
    variables = {
        'name': '张三',
        # 'other_field': '其他值',
    }

    # 渲染模板
    content = template.render(variables)

    # 创建Word文档并写入内容
    doc = Document()
    doc.add_paragraph(content)

    # 保存文档
    response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
    response['Content-Disposition'] = 'attachment; filename="generated_document.docx"'
    doc.save(response)

    return response
